import React, { useRef, useEffect, useState } from 'react'
import { Canvas, useFrame, useLoader } from '@react-three/fiber'
import { FBXLoader } from 'three/examples/jsm/loaders/FBXLoader'
import { OrbitControls } from '@react-three/drei'
import * as THREE from 'three'

// 3D数字人组件
function DigitalHumanModel({ action, position = [0, 0, 0] }) {
  const meshRef = useRef()
  const mixerRef = useRef()
  const [model, setModel] = useState(null)
  const [animations, setAnimations] = useState([])

  // 加载FBX模型
  useEffect(() => {
    const loader = new FBXLoader()
    loader.load('/models/肘击.fbx', (fbx) => {
      // 设置模型
      fbx.scale.setScalar(0.01) // 调整模型大小
      fbx.position.set(...position)
      setModel(fbx)

      // 设置动画
      if (fbx.animations && fbx.animations.length > 0) {
        setAnimations(fbx.animations)
        const mixer = new THREE.AnimationMixer(fbx)
        mixerRef.current = mixer
        
        // 播放第一个动画
        const action = mixer.clipAction(fbx.animations[0])
        action.play()
      }
    })
  }, [])

  // 动画更新
  useFrame((state, delta) => {
    if (mixerRef.current) {
      mixerRef.current.update(delta)
    }
  })

  // 切换动作
  useEffect(() => {
    if (mixerRef.current && animations.length > 0) {
      // 停止当前动画
      mixerRef.current.stopAllAction()
      
      // 根据动作名称播放对应动画
      const actionIndex = getActionIndex(action)
      if (actionIndex >= 0 && actionIndex < animations.length) {
        const newAction = mixerRef.current.clipAction(animations[actionIndex])
        newAction.play()
      }
    }
  }, [action, animations])

  const getActionIndex = (actionName) => {
    const actionMap = {
      '默认动作': 0,
      '肘击': 0,
      '拐': 1,
      '点头': 2,
      '摇头': 3
    }
    return actionMap[actionName] || 0
  }

  if (!model) {
    return null
  }

  return <primitive object={model} ref={meshRef} />
}

// 场景组件
function Scene({ action }) {
  return (
    <>
      <ambientLight intensity={0.6} />
      <directionalLight position={[10, 10, 5]} intensity={1} />
      <DigitalHumanModel action={action} position={[0, -1, 0]} />
      <OrbitControls 
        enablePan={false}
        enableZoom={true}
        enableRotate={true}
        minDistance={2}
        maxDistance={5}
      />
    </>
  )
}

// 主组件
function DigitalHuman({ action = '默认动作' }) {
  return (
    <div style={{ width: '100%', height: '100%' }}>
      <Canvas
        camera={{ position: [0, 0, 3], fov: 50 }}
        style={{ background: 'transparent' }}
      >
        <Scene action={action} />
      </Canvas>
    </div>
  )
}

export default DigitalHuman
